package com.ahwei.shop.auth.security.handler;

import com.ahwei.r.R;
import com.ahwei.r.ResultCode;
import com.ahwei.shop.auth.util.ResponseUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author：ahWei
 * Email: ahwei163@qq.com
 * Date: 2022-05-19 17:20:17
 * Description: 身份认证失败处理！
 */
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
	@Resource
	private ResponseUtils responseUtils;
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
		String msg = "登录失败";
		if (exception instanceof LockedException) {
			msg = "账户被锁定，请联系管理员!";
		} else if (exception instanceof CredentialsExpiredException) {
			msg = "密码过期，请联系管理员!";
		} else if (exception instanceof AccountExpiredException) {
			msg = "账户过期，请联系管理员!";
		} else if (exception instanceof DisabledException) {
			msg = "账户被禁用，请联系管理员!";
		} else if (exception instanceof BadCredentialsException) {
			// 用户名或者密码输入错误，一般只给一个模糊的提示，即「用户名或者密码输入错误，请重新输入」
			msg = "用户名或者密码输入错误，请重新输入!";
		}

		// 返回的R对象
		responseUtils.outWriter(R.error(ResultCode.LOGIN_ERROR,msg), HttpStatus.UNAUTHORIZED.value(),response);

	}
}